package com.service.impl;

import com.constant.FileUploadConstant;
import com.result.Result;
import com.service.FileUploadService;
import com.utils.RandomUtils;
import com.vo.ApkUplaodResultVo;
import com.vo.FileUploadResultVo;
import lombok.extern.slf4j.Slf4j;
import net.dongliu.apk.parser.ApkFile;
import net.dongliu.apk.parser.bean.ApkMeta;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
@Slf4j
@Service
public class FileUploadServiceImpl implements FileUploadService {



    @Override
    public Result<FileUploadResultVo> uploadVideo(HttpServletRequest request, HttpServletResponse response, MultipartFile originFile) {
        //校验文件格式
        if (originFile == null) {
            return new Result().error("未检测到文件");
        }
        if (originFile.getOriginalFilename() == null) {
            return new Result().error("文件名为空");
        }
        String suffixs = ".mp4.rmvb.avi.flv.3gp.wmv";
        String suffix = originFile.getOriginalFilename().substring(originFile.getOriginalFilename()
                .lastIndexOf("."));
        if (!suffixs.contains(suffix)) {
            return new Result().error( "视频格式有误，rmvb, mp4, avi,flv,wmv,3gp视频格式中的一种");
        }
        InputStream in = null;
        try {
            in = originFile.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //FileUploadConstant.IMG_UPLOAD_PATH;
        String uuidOriginalName = RandomUtils.uuid()+originFile.getOriginalFilename();
        File file = new File(FileUploadConstant.VIDEO_UPLOAD_PATH+uuidOriginalName);
        if (!file.getParentFile().exists()){
            file.mkdirs();
        }
        // 开始保存到本地
        String fileName = originFile.getOriginalFilename();
        //新生成一个文件
        OutputStream os = null;
        try {
            os = new FileOutputStream(file);
            byte[] buffer = new byte[10240];
            while (-1 != (in.read(buffer, 0, buffer.length))) {
                os.write(buffer);
            }
            os.close();
            in.close();
            String relativePath = "/videos/" + uuidOriginalName;
            String fullPath =  relativePath;
            FileUploadResultVo resultVo = new FileUploadResultVo();
            resultVo.setFilePath(relativePath);
            resultVo.setPreviewPath(fullPath);
            return new Result().ok(resultVo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result<>().error( "上传失败");
    }

    @Override
    public Result<ApkUplaodResultVo> uploadApk(HttpServletRequest request, HttpServletResponse response, MultipartFile originFile) {
        //校验文件格式
        if (originFile == null) {
            System.out.println("未检测到文件");
            return new Result<>().error( "未检测到文件");
        }
        if (originFile.getOriginalFilename() == null) {
            System.out.println("文件名为空");
            return new Result<>().error(  "文件名为空");
        }
        String suffixs = ".apk";
        String suffix = originFile.getOriginalFilename().substring(originFile.getOriginalFilename()
                .lastIndexOf("."));
        if (!suffixs.contains(suffix)) {
            System.out.println("文件格式有误，必须为apk");
            return new Result<>().error( "文件格式有误，必须为apk");
        }
//        InputStream in = null;
//        try {
//            in = originFile.getInputStream();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        //FileUploadConstant.IMG_UPLOAD_PATH;
        String uuidOriginalName = RandomUtils.uuid()+"_"+originFile.getOriginalFilename();
        File file = new File(FileUploadConstant.APK_UPLOAD_PATH+uuidOriginalName);
        System.out.println("apk_path:"+file.getAbsolutePath());
        if (!file.getParentFile().exists()){
            file.mkdirs();
        }
        try {
            originFile.transferTo(file.getAbsoluteFile());
        } catch (IOException e) {
            e.printStackTrace();
            return  new Result().error( "上传失败");
        }
        // 开始保存到本地
        //新生成一个文件
        OutputStream os = null;
        try {
//            os = new FileOutputStream(file);
//            byte[] buffer = new byte[10240];
//            while (-1 != (in.read(buffer, 0, buffer.length))) {
//                os.write(buffer);
//            }
//            os.close();
//            in.close();
            ApkFile apkFile = new ApkFile(new File(file.getAbsolutePath()));
            ApkMeta apkMeta = apkFile.getApkMeta();
            if (!FileUploadConstant.APK_PACKAGE_NAME.equals(apkMeta.getPackageName())){
                if (file.exists()){
                    file.delete();
                }
                return  new Result().error( "请上传正确的apk文件");
            }
            String relativePath = "/apk/" + uuidOriginalName;
            ApkUplaodResultVo vo = new ApkUplaodResultVo();
            vo.setFilePath(relativePath);
            vo.setVersionCode(apkMeta.getVersionCode());
            vo.setVersionName(apkMeta.getVersionName());
            vo.setPackageName(apkMeta.getPackageName());
            return new Result().ok(vo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  new Result().error( "上传失败");
    }


    @Override
    public Result<FileUploadResultVo> uploadBookImg(HttpServletRequest request, HttpServletResponse response, MultipartFile originFile) {
        //校验文件格式
        if (originFile == null) {
            return new Result().error(  "未检测到文件");
        }
        if (originFile.getOriginalFilename() == null) {
            return new Result().error(  "文件名为空");
        }
        String suffixs = ".bmp.jpg.png.BMP.JPG.PNG";
        String suffix = originFile.getOriginalFilename().substring(originFile.getOriginalFilename()
                .lastIndexOf("."));
        if (!suffixs.contains(suffix)) {
            return new Result().error(  "图片格式有误，必须为bmp, jpg, png图片格式中的一种");
        }
        InputStream in = null;
        try {
            in = originFile.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String uuidOriginalName = RandomUtils.uuid()+originFile.getOriginalFilename();
        File file = new File(FileUploadConstant.IMG_UPLOAD_PATH+uuidOriginalName);
        if (!file.getParentFile().exists()){
            file.mkdirs();
        }
        // 开始保存到本地
        String fileName = originFile.getOriginalFilename();
        //新生成一个文件
        OutputStream os = null;
        try {
            os = new FileOutputStream(file);
            byte[] buffer = new byte[10240];
            while (-1 != (in.read(buffer, 0, buffer.length))) {
                os.write(buffer);
            }
            os.close();
            in.close();
            String relativePath = "/imgs/" + uuidOriginalName;
            String fullPath =  relativePath;
            FileUploadResultVo resultVo = new FileUploadResultVo();
            resultVo.setFilePath(relativePath);
            resultVo.setPreviewPath(fullPath);
            return new Result().ok( resultVo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result().error( "上传失败");
    }


    @Override
    public Result<String> downloadImg(HttpServletRequest request, HttpServletResponse response) {
        FileInputStream fileInputStream = null;
        ServletOutputStream out = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("image/jpeg");
        try {
            //读取文件到response
            File newFile = new File("D:\\data\\upload\\imgs\\支付相关表.jpg");
            if (newFile.exists()) {
                System.out.println("文件存在!!!可以下载");
                fileInputStream = new FileInputStream(newFile);
                out = response.getOutputStream();
                byte[] bufferOut = new byte[1024];
                int count = 0;
                int bytes = 0;
                // 上传文件
                while ((bytes = fileInputStream.read(bufferOut)) != -1) {
                    // 上传文件(一份)
                    out.write(bufferOut, 0, bytes);
                    // 计算当前已上传的大小
                    count += bytes;
                }
                out.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return new Result<>().ok();
    }
}
